const router = require('koa-router')()
const UserModule = require('../modules/user')
const auth = require('../middleware/session')

router.prefix('/user_session')

router.post('/login', async function (ctx) {
  let { name, password } = ctx.request.body
  let user = await UserModule.findOne({ name, password })
  if (user) {
    ctx.session.user = user
    ctx.body = user
  } else {
    ctx.body = {
      code: 400,
      message: '用户不存在'
    }
    ctx.response.status = 400
  }
})

router.get('/get', auth,  async function (ctx) {
  ctx.body = await UserModule.findOne(ctx.request.body.id)
} )

router.post('/create', async function (ctx, next) {
  const {
      name, password
  } = ctx.request.body
  await UserModule.add({
      name, password
  })
  ctx.body = {
    return: true
  }
})


router.get('/bar', function (ctx, next) {
  ctx.body = 'this is a users/bar response'
})

module.exports = router
